package com.dxg.msns.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxg.msns.user.mapper.MusicGradeMapper;
import com.dxg.msns.user.mapper.UserMapper;
import com.dxg.msns.user.pojo.MusicGrade;
import com.dxg.msns.user.pojo.User;
import com.dxg.msns.user.service.SingerService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
// import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SingerServiceImpl implements SingerService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MusicGradeMapper musicGradeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<User> querySingersByPage(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_singer", 1);
        if(name != null && !"".equals(name)) {
            queryWrapper.like("uname", name);
        }
        List<User> singers = userMapper.selectList(queryWrapper);
        System.out.println(singers);
        QueryWrapper<MusicGrade> queryWrapperMusicGrade = new QueryWrapper<>();
        List<MusicGrade> musicGrades = this.musicGradeMapper.selectList(queryWrapperMusicGrade);
        Map<String, Double> singerAvgMap = calculateAverageScoreBySinger(musicGrades);
        singers.sort((u1, u2) -> {
            Double avg1 = singerAvgMap.getOrDefault(u1.getId(), 0.0);
            Double avg2 = singerAvgMap.getOrDefault(u2.getId(), 0.0);
            return avg2.compareTo(avg1); // 降序排序
        });
        return singers;
    }
    @Override
    public User querySingersByUid(String uid) {
        return userMapper.selectSingerByUid(uid); // 若无结果会返回null
}


    @Override
    public List<User> getApplySinger(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_singer", -1);
        if(name != null && !"".equals(name)) {
            queryWrapper.like("uname", name);
        }
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> getNotSinger() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_singer", 0);
        return userMapper.selectList(queryWrapper);
    }

    public Map<String, Double> calculateAverageScoreBySinger(List<MusicGrade> musicGrades) {
        // 过滤状态为 0 的有效数据
        return musicGrades.stream()
                .filter(g -> g.getStatus() != null && g.getStatus() == 0)
                .collect(Collectors.groupingBy(
                        MusicGrade::getUserId,
                        Collectors.averagingInt(MusicGrade::getMusicGrade)));
    }

}
